#!/usr/bin/env python3

import argparse
import json
import os
import random
import sys

# 修改导入路径，确保从项目根目录下的 lib 目录导入模块
# 获取当前脚本所在目录（gen_anki_import_data）
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取项目根目录（src 的父目录）
project_root = os.path.dirname(current_dir)
sys.path.append(project_root)

from lib.anki import generate_anki_import_file
from lib.my_tts import gen_audio_by_bytedance
from lib.my_pic_searcher.my_pic_searcher import get_img_only_by_en_from_pexels

anki_media_dir = r'C:\Users\XYQTJ\AppData\Roaming\Anki2\User 1\collection.media'

def genRndHexStr():
    random_string = secrets.token_hex(16)
    hash_object = hashlib.sha256()
    hash_object.update(random_string.encode('utf-8'))
    hex_dig = hash_object.hexdigest()
    return hex_dig

def genAudioFileName(name):
    return name + '.mp3'

def genAudios(texts, output_dir):
    for text in texts:
        audio_path = os.path.join(output_dir, genAudioFileName(text))
        gen_audio_by_bytedance(text, audio_path)

def genAudiosByWords(en_words, cn_words, output_dir):
    isConflict = False
    for item in en_words:
        audio_name = genAudioFileName(item)
        audio_path = os.path.join(anki_media_dir, audio_name)
        if os.path.exists(audio_path):
            print(audio_path + " already exist")
            isConflict = True        

    for item in cn_words:
        audio_name = genAudioFileName(item)
        audio_path = os.path.join(anki_media_dir, audio_name)
        if os.path.exists(audio_path):
            print(audio_path + " already exist")
            isConflict = True        

    #print(genRndHexStr())
    #if isConflict:
    #    return False

    genAudios(en_words, output_dir)
    genAudios(cn_words, output_dir)
    return True
        
def genAnkiImportData(output_dir, word_groups):
    grp_idx = 1
    for group in word_groups:
        cards = []
        word_cnt = len(group[0])
        # deck_name = deck_pfx + str(deck_idx_start + grp_idx)
        import_file_path = output_dir + '/anki_import_data' + "{:02}".format(grp_idx) + '.txt'
        # grp_idx += 1
        # print('word count is ' + str(word_cnt))
        en_words = group[0]
        cn_words = group[1]
        
        for index in range(word_cnt):
            en_word = en_words[index]
            cn_word = cn_words[index]
            img = en_word + ".jpg"
            
            deck_name_rr = deck_pfx + "1_认读::20250408::" + "{:02}".format(deck_idx_start + grp_idx);
            # listen
            card5 = {}
            card5['deck_name'] = deck_name_rr
            card5['front'] = "<h1>" + en_word + "</h1>[sound:这个英文怎么读？.mp3]"
            card5['back'] = "<img src=\"" + img + "\"><br>[sound:" + en_word +".mp3]"
            cards.append(card5)
           
            card1 = {}
            card1['deck_name'] = deck_name_rr
            card1['front'] = "[sound:" + en_word +".mp3][sound:的中文意思是什么？.mp3]"
            card1['back'] = "<h1>" + cn_word + "</h1><br><img src=\"" + img + "\"><br>[sound:" + cn_word +".mp3]"
            cards.append(card1)
           
            card3 = {}
            card3['deck_name'] = deck_name_rr
            card3['front'] = "<h1>" + en_word + "</h1>[sound:这个的中文意思是什么？.mp3]"
            card3['back'] = "<h1>" + cn_word + "</h1><br><img src=\"" + img + "\"><br>[sound:" + cn_word +".mp3]"
            cards.append(card3)
            
            card4 = {}
            card4['deck_name'] = deck_name_rr
            card4['front'] = "[sound:什么英文的意思是.mp3][sound:" + cn_word + ".mp3]"
            card4['back'] = "<h1>" + en_word + "</h1><img src=\"" + img + "\"><br>[sound:" + en_word +".mp3]"
            cards.append(card4)
            
            deck_name_lw = deck_pfx + "2_听写::20250408::" + "{:02}".format(deck_idx_start + grp_idx);
            # write
            card2 = {}
            card2['deck_name'] = deck_name_lw
            card2['front'] = "[sound:" + en_word +".mp3][sound:怎么写？.mp3]"
            card2['back'] = "<h1>" + en_word + "</h1>"
            cards.append(card2)
        grp_idx += 1
        generate_anki_import_file(cards, import_file_path)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Generate Anki import data from word groups in a JSON file.")
    parser.add_argument("json_file", help="Path to the JSON file containing word groups")
    args = parser.parse_args()

    with open(args.json_file, 'r', encoding='utf-8') as f:
        input_file = json.load(f)

    # print(input_file)
    word_groups = input_file['word groups']
    # print(word_groups)
    deck_pfx = input_file['deck name prefix']
    deck_idx_start = input_file['deck name index start']
    # print ('deck name prefix is ' + deck_pfx + ' and index start is ' + str(deck_idx_start) + '.')
    need_gen_anki_import_files = input_file['need generate anki import files']
    # print ('need generate anki import file is ' + str(need_gen_anki_import_files) + '.')
    need_gen_audios = input_file['need generate audios']
    # print ('need generate audios is ' + str(need_gen_audios) + '.')
    need_gen_pics = input_file['need generate pictures']
    # print ('need generate pictures is ' + str(need_gen_pics) + '.')
    output_dir = input_file['output directory']
    # print ('output directory is "' + output_dir + '".')
    anki_import_data_file_name = input_file['anki import data file name']
    # print ('anki import data file name is ' + anki_import_data_file_name + '.')

    # exit(0)

    # create output directory
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    anki_import_data_file_path = os.path.join(output_dir, anki_import_data_file_name)
    
    if need_gen_anki_import_files:
        genAnkiImportData(output_dir, word_groups)
    
    if need_gen_audios:
        for grp in word_groups:
            word_cnt = len(grp[0])
            en_words = grp[0]
            cn_words = grp[1]
            for index in range(word_cnt):
                en_word = en_words[index]
                audio_name = en_word + '.mp3'
                audio_path = os.path.join(output_dir, audio_name)
                gen_audio_by_bytedance(en_word, audio_path)
                cn_word = cn_words[index]
                audio_name = cn_word + '.mp3'
                audio_path = os.path.join(output_dir, audio_name)
                gen_audio_by_bytedance(cn_word, audio_path)

    if need_gen_pics:
        for grp in word_groups:
            en_words = grp[0]
            get_img_only_by_en_from_pexels(en_words, output_dir)
                